//
//  Weather.swift
//  MoYoung
//
//  Created by sylar on 16/11/1.
//  Copyright © 2016年 sylar. All rights reserved.
//

import UIKit
import Alamofire
import CoreLocation
import Contacts
import CRPEarPhone
import RxSwift
import RxCocoa

public class Weather:  NSObject, CLLocationManagerDelegate {
    
    public static let shared = Weather()
    
    private let locationManager:CLLocationManager = CLLocationManager()
    
    public var autoGps: Bool {
        get {
            return UserDefaults.standard.bool(forKey: "autoGps")
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "autoGps")
        }
    }
    
    public var city: String {
        get{
            return UserDefaults.standard.string(forKey: "city") ?? ""
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "city")
            guard newValue != self.cityName.value else {
                return
            }
            self.cityName.accept(newValue)
        }
    }
    
    public var cityEN: String {
        get{
            return UserDefaults.standard.string(forKey: "cityEN") ?? ""
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "cityEN")
            guard newValue != self.cityName.value else {
                return
            }
            self.cityName.accept(newValue)
        }
    }
    
    public var tempformat: TemperatureType {
        get {
            let raw = UserDefaults.standard.integer(forKey: "tempformat")
            return TemperatureType.init(rawValue: raw) ?? .degreeCelsius
        }
        set {
            UserDefaults.standard.setValue(newValue.rawValue, forKey: "tempformat")
            guard newValue != self.temprateUnit.value else {
                return
            }
            self.temprateUnit.accept(newValue)
        }
    }  //0: 摄氏度，1：华氏度
    
    public var openWeatherCity: String {
        get{
            return UserDefaults.standard.string(forKey: "openWeatherCity") ?? ""
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "openWeatherCity")
        }
    }
    
    private var gpsOpenWeatherCity = ""
    
    private var oldOpenWeatherCity: String {
        get{
            return UserDefaults.standard.string(forKey: "oldOpenWeatherCity") ?? ""
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "oldOpenWeatherCity")
        }
    }
    
    private var OpenWeatherForecastData: [[String:Any]] = [[:]]{
        didSet{
            UserDefaults.standard.setValue(OpenWeatherForecastData, forKey: "OpenWeatherForecastData")
        }
    }
    
    private var openWeatherRealTimeData: [String:Any] = [:]{
        didSet{
            UserDefaults.standard.setValue(openWeatherRealTimeData, forKey: "openWeatherRealTimeData")
        }
    }
    
    public var cityGPSInfo:[String:Double] = [:]{
        didSet{
            UserDefaults.standard.setValue(cityGPSInfo, forKey: "cityGPSInfo")
        }
    }
    
    private var isGettingOpenWeather: Bool = false
    
    /// 每小时更新
    public let updateEveryHour = BehaviorRelay<Bool>(value: false)
    public let temprateUnit = BehaviorRelay<TemperatureType>(value: .degreeCelsius)
    public let cityName = BehaviorRelay<String>(value: "")
    public let autoGPSEnable = BehaviorRelay(value: false)
    
    override init() {
        
        if let OpenWeatherForecastData = UserDefaults.standard.value(forKey: "OpenWeatherForecastData") as? [[String:Any]] {
            self.OpenWeatherForecastData = OpenWeatherForecastData
        }
        if let openWeatherRealTimeData = UserDefaults.standard.value(forKey: "openWeatherRealTimeData") as? [String: Any]{
            self.openWeatherRealTimeData = openWeatherRealTimeData
        }
        if let cityGPSInfo = UserDefaults.standard.value(forKey: "cityGPSInfo") as? [String:Double]{
            self.cityGPSInfo = cityGPSInfo
        }
    }
    
    public func setConfig() {
        
        let updateHour = UserDefaults.standard.bool(forKey: "kUpdateWeatherEveryHour")
        self.updateEveryHour.accept(updateHour)
        
        if (getCurrentLanguage() == "cn"){
            self.cityName.accept(Weather.shared.city)
        }else {
            self.cityName.accept(Weather.shared.cityEN)
        }
        
        self.temprateUnit.accept(self.tempformat)
        self.autoGPSEnable.accept(self.autoGps)
        
        self.updateEveryHour
            .skip(1)
            .distinctUntilChanged()
            .subscribe(onNext: { value in
                UserDefaults.standard.setValue(value, forKey: "kUpdateWeatherEveryHour")
            }).disposed(by: rx.disposeBag)
        
        self.autoGPSEnable
            .skip(1)
            .distinctUntilChanged()
            .subscribe(onNext: { value in
                self.autoGps = value
                
                if value {
                    self.city = ""
                    self.get()
                }
            }).disposed(by: rx.disposeBag)
        
        self.cityName.skip(1).distinctUntilChanged()
            .subscribe(onNext: { _ in
                self.get()
            }).disposed(by: rx.disposeBag)
        
        self.temprateUnit.skip(1).distinctUntilChanged()
            .subscribe(onNext: { _ in
                self.get()
            }).disposed(by: rx.disposeBag)
        
        self.updateEveryHour
            .flatMapLatest { enable in
                if enable {
                    return Observable<Int>.timer(.seconds(3600), period: .seconds(1), scheduler: ConcurrentDispatchQueueScheduler(qos: .background)).mapToVoid()
                }
                return Observable.just(())
            }
            .subscribe(onNext: { _ in
                self.get()
            }).disposed(by: rx.disposeBag)
    }
    
    public func get() {
    
        //开启自动定位天气时，每次获取定位信息再获取天气信息
        if (self.autoGps) {
            self.updateLocation()
        }
        else {
            //获取设置的城市的天气，城市为空时定位再获取天气
            if let city = UserDefaults.standard.value(forKey: "city") {
                self.city = city as! String
                
                if (self.city != "") {
                    self.getByCN()
                    return
                }
            }
            //self.updateLocation()
        }
    }

    private func updateLocation() {
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 100
        locationManager.requestAlwaysAuthorization()
        
        if (CLLocationManager.locationServicesEnabled()) {
            GeoLocationService.instance.authorized
                .drive(onNext: { value in
                    if value {
                        self.locationManager.startUpdatingLocation()
                    } else {
                        if getCurrentLanguage() == "cn"{
                            self.getCityByIp()
                        }else {
                            self.getOpenWeather()
                        }
                    }
                }).disposed(by: rx.disposeBag)
        } else {
            if getCurrentLanguage() == "cn"{
                getCityByIp()
            }else {
                getOpenWeather()
            }
        }
    }
    
    func getCityByIp() {
        let ipUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=myip&accessKey=alibaba-inc"
        AF.request(ipUrl, parameters:nil).responseJSON { response in
            switch response.result {
            case .success(let json):
                let data = json as AnyObject
                let code = data.value(forKey: "code") as? Int
                if  code != nil && (code == 0) {
                    let ipData = data.value(forKey: "data") as? Dictionary<String, Any>
                    if ipData != nil {
                        let city:String? = ipData!["city"] as? String
                        if(city != nil && city != "XX" && city != ""){
                            self.city = city!
                            self.getByCN()
                        }
                    }
                }
            case .failure(let error):
                log.debug(error)
            }
        }
    }
    
    //定位改变执行，可以得到新位置、旧位置
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationManager.stopUpdatingLocation()
        //获取最新的坐标
        let currLocation = locations.last!
        let geocoder: CLGeocoder = CLGeocoder()
        if (getCurrentLanguage() != "cn") {
            geocoder.reverseGeocodeLocation(currLocation) { (placemark: [CLPlacemark]?, error:Error?) in
                geocoder.reverseGeocodeLocation(currLocation) { (placemarks: [CLPlacemark]?, error:Error?) in
                    if (error == nil) {
                        if let placemark = placemarks?[0] {
                            log.debug("placemark =\(placemark)")
                            if placemark.locality != nil {
                                self.city = placemark.locality!
                            }else if placemark.administrativeArea != nil{
                                self.city = placemark.administrativeArea!
                            }
                            self.getPostalAddress(placemark: placemark)
                        }
                    }else{
                        log.debug("placemarks =\(error)")
                    }
                }
            }
            
            
            
        }
        else {
            geocoder.reverseGeocodeLocation(currLocation) { (placemark: [CLPlacemark]?, error:Error?) in
                geocoder.reverseGeocodeLocation(currLocation) { (placemarks: [CLPlacemark]?, error:Error?) in
                    if (error == nil) {
                        if let placemark = placemarks?[0] {
                            if placemark.locality != nil {
                                self.city = placemark.locality!
                                self.getByCN()
                            }
                        }
                    }
                }
            }
        }
        
    }
    
    func getPostalAddress(placemark:CLPlacemark){
        if #available(iOS 11.0, *) {
            if let postalAddress = placemark.postalAddress{
                gpsOpenWeatherCity = postalAddress.city + "," + postalAddress.country
            }
        } else {
            if let addressDictionary = placemark.addressDictionary{
                if let city = addressDictionary["City"] as? String, let country = addressDictionary["Country"] as? String{
                    gpsOpenWeatherCity = city + "," + country
                }
            }
        }
        getOpenWeather()
    }
    

    
    func getByCN() {
//        if (BandManager.sharedInstance.isConnected()) {
            //网络请求数据为JSON
//            AF.request(apiWeatherCN, parameters:["city": self.city]).responseJSON { response in
            //网络请求数据为加密的String
            AF.request(newAPIWeatherCN, parameters: ["city": self.city]).responseString { (response) in
                switch response.result{
                case .success(let encryptString):
                    do {
                        if let decrypt = encryptString.threeDESEncryptOrDecrypt(op: 0){
                            let encryptData = decrypt.data(using: .utf8)
                            let data = try JSONSerialization.jsonObject(with: encryptData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                            log.debug("Weather data = \(data)")
                            let code = data.value(forKey: "code") as? Int
                            if let codeInt = code, codeInt == 0 {
                                if let weather = data.value(forKey: "weather") as? Dictionary<String, Any>{
                                    //实时
                                    if let sk = weather["sk"] as? Dictionary<String, Any> {
                                        let skWeather = sk["weather"] as? String
                                        let skTemp = sk["temp"] as? String
                                        let skPm25 = (sk["pm25"]) as? Int
                                        let skFestival = sk["festival"] as? String
                                        let skLunar = sk["lunar"] as? String
                                        let weather_id = sk["weather_id"]  as? String
                                        
                                        if skWeather != nil && skTemp != nil && skPm25 != nil && skFestival != nil && skLunar != nil && weather_id != nil {
                                            let type = self.parseType(weather_id!)
                                            var skTempInt = Int(skTemp!)
                                            if self.tempformat == .fahrenheit{
                                                skTempInt = Int(Double(skTempInt!) * 1.8) + 32
                                            }
                                            guard skTempInt != nil else {
                                                return
                                            }

                                            if let today = weather["today"] as? Dictionary<String, Any>{
                                                if let info = today["info"] as? Dictionary<String,Any>,let dawnArray = info["dawn"] as? [String],let nightArray = info["night"] as? [String]{
                                                    if let dawn = dawnArray.first, let night = nightArray.first{
                                                        let sunriseTimeArray = changeTimeTo24Format(time: dawn)
                                                        let sunsetTimeArray = changeTimeTo24Format(time: night)
                                                        if sunriseTimeArray.count == 2 && sunsetTimeArray.count == 2{
                                                            let newWeatherInfo = CRPWeather(type: type, temp: skTempInt!, pm25: 0, sunriseHour: sunriseTimeArray[0], sunriseMin: sunriseTimeArray[1], sunsetHour: sunsetTimeArray[0], sunsetMin: sunsetTimeArray[1], city: self.city, tempUnit: self.tempformat.rawValue)
                                                            BluetoothManager.shared.sendWeather(weather: newWeatherInfo)
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        
                                        
                                    }
                                    
                                    
                                    //预报
                                    let future = weather["future"] as? [Dictionary<String, Any>]
                                    var forecast = [[String]]()
                                    if future != nil {
                                        for v in future! {
                                            let weather = v["weather"] as? String
                                            let temp:String? = v["temperature"] as? String
                                            let weather_id = v["weather_id"] as? Dictionary<String,String>
                                            var fa: String?
                                            if weather_id != nil {
                                                fa = weather_id!["fa"] as? String
                                            }
                                            if weather != nil && temp != nil && fa != nil {
                                                let temp2 = temp!.replacingOccurrences(of: "℃", with: "")
                                                var tempArr = temp2.components(separatedBy: "~")
                                                let type = String(self.parseType(fa!))
                                                guard tempArr.count >= 2 else {
                                                    return
                                                }
                                                guard let maxTemp = Double(tempArr[0]) else {
                                                    return
                                                }
                                                guard let minTemp = Double(tempArr[1]) else {
                                                    return
                                                }
                                                if self.tempformat == .fahrenheit{
                                                    tempArr[0] = String(Int(Double(tempArr[0])! * 1.8) + 32)
                                                    tempArr[1] = String(Int(Double(tempArr[1])! * 1.8) + 32)
                                                }
                                                
                                                forecast.append([type, tempArr[0], tempArr[1], type])
                                            }
                                        }
                                        self.writeForecast(forecast)
                                    }
                                    
                                }
                            }
                        }
                    }catch(let error){
                        log.debug("encrypt error =\(error )")
                    }
                case .failure(let error):
                    log.debug(error)
                }
            }
        }
    
    public func getOpenWeather() {
        var weatherCityName = self.gpsOpenWeatherCity
        if self.cityEN != ""{
            weatherCityName = self.cityEN
        }
        if openWeatherCity != ""{
            weatherCityName = openWeatherCity
        }
        if weatherCityName != "" && weatherCityName != "," && !self.isGettingOpenWeather {
            if weatherCityName != oldOpenWeatherCity || getIsUpdateRealTimeWeatherData(){
                self.isGettingOpenWeather = true
                if let lat = cityGPSInfo["lat"], let lon = cityGPSInfo["lon"] {
                    AF.request(openWeatherCurrentWeatherByGPS, parameters: ["lat": lat,"lon":lon]).responseString { (response) in
                        self.isGettingOpenWeather = false
                        switch response.result{
                        case .success(let encryptString):
                            if let decrypt = encryptString.threeDESEncryptOrDecrypt(op: 0){
                                self.parseTodayOpenWeather(json: decrypt, cityName: weatherCityName)
                            }
                        case .failure(let error):
                            log.debug(error)
                        }
                    }
                }else {
                    AF.request(openWeatherCurrentWeather, parameters: ["city": weatherCityName]).responseString { (response) in
                        self.isGettingOpenWeather = false
                        switch response.result{
                        case .success(let encryptString):
                            if let decrypt = encryptString.threeDESEncryptOrDecrypt(op: 0){
                                self.parseTodayOpenWeather(json: decrypt, cityName: weatherCityName)
                            }
                        case .failure(let error):
                            log.debug(error)
                        }
                    }
                }
            }else {
                if self.openWeatherRealTimeData != nil {
                    if let cityName = openWeatherRealTimeData["city"] as? String,let skTempInt = openWeatherRealTimeData["skTempInt"] as? Double,let type = openWeatherRealTimeData["type"] as? Int{
                        var temp = Int(lround(skTempInt))
                        if self.tempformat == .fahrenheit{
                            temp = Int(skTempInt * 1.8) + 32
                        }
                        
                        if let sunrise = openWeatherRealTimeData["sunrise"] as? Int, let sunset = openWeatherRealTimeData["sunset"] as? Int, let timezone = openWeatherRealTimeData["timezone"] as? Int{
                            let timeDiff = timezone - NSTimeZone.local.secondsFromGMT()
                            let format = DateFormatter()
                            format.dateFormat = "HH:mm"
                            let sunriseTime = format.string(from: Date(timeIntervalSince1970: TimeInterval(Double(sunrise + timeDiff))))
                            let sunsetTime = format.string(from: Date(timeIntervalSince1970: TimeInterval(Double(sunset + timeDiff))))
                            let sunriseTimeArray = changeTimeTo24Format(time: sunriseTime)
                            let sunsetTimeArray = changeTimeTo24Format(time: sunsetTime)
                            if sunriseTimeArray.count == 2 && sunsetTimeArray.count == 2{
                                let newWeatherInfo = CRPWeather(type: type, temp: temp, pm25: 0, sunriseHour: sunriseTimeArray[0], sunriseMin: sunriseTimeArray[1], sunsetHour: sunsetTimeArray[0], sunsetMin: sunsetTimeArray[1], city: cityName, tempUnit: self.tempformat.rawValue)
                                BluetoothManager.shared.sendWeather(weather: newWeatherInfo)
                            }
                            
                        }
                    }
                    
                }
                
            }
            
            getOpenWeatherForecast(weatherCityName: weatherCityName)
        }else {
            if self.isGettingOpenWeather{
                self.isGettingOpenWeather = false
            }
        }
    }
    
    func parseTodayOpenWeather(json: String,cityName: String){
        do {
            if let data = json.data(using: .utf8){
                let ditc = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                var codeCheck: Bool = false
                if let dataCodeStr = ditc.value(forKey: "cod") as? String, dataCodeStr == "200"{
                    codeCheck = true
                }
                if let dataCodeInt = ditc.value(forKey: "cod") as? Int, dataCodeInt == 200{
                    codeCheck = true
                }
                if codeCheck {
                    if let main = ditc["main"] as? [String:Any]{
                        if let weathers = ditc["weather"] as? [[String: Any]], weathers.count > 0{
                            if let weather = weathers.first{
                                if let typeId = weather["id"] as? Int,let realTemp = main["temp"] as? Double{
                                    let type = self.parseOpenWeather(typeId)
                                    var skTempInt = Int(lround(realTemp))
                                    if self.tempformat == .fahrenheit{
                                        skTempInt = Int(realTemp * 1.8) + 32
                                    }

                                    var realTimeWeather:[String:Any] = [:]
                                    realTimeWeather["city"] = cityName
                                    realTimeWeather["skTempInt"] = realTemp
                                    realTimeWeather["type"] = type
                                    if let sys = ditc["sys"] as? [String: Any]{
                                        if let sunrise = sys["sunrise"] as? Int, let sunset = sys["sunset"] as? Int, let timezone = ditc["timezone"] as? Int{
                                            realTimeWeather["sunrise"] = sunrise
                                            realTimeWeather["sunset"] = sunset
                                            realTimeWeather["timezone"] = timezone
                                            let timeDiff = timezone - NSTimeZone.local.secondsFromGMT()
                                            let format = DateFormatter()
                                            format.dateFormat = "HH:mm"
                                            let sunriseTime = format.string(from: Date(timeIntervalSince1970: TimeInterval(Double(sunrise + timeDiff))))
                                            let sunsetTime = format.string(from: Date(timeIntervalSince1970: TimeInterval(Double(sunset + timeDiff))))
                                            let sunriseTimeArray = changeTimeTo24Format(time: sunriseTime)
                                            let sunsetTimeArray = changeTimeTo24Format(time: sunsetTime)
                                            if sunriseTimeArray.count == 2 && sunsetTimeArray.count == 2{
                                                let newWeatherInfo = CRPWeather(type: type, temp: skTempInt, pm25: 0, sunriseHour: sunriseTimeArray[0], sunriseMin: sunriseTimeArray[1], sunsetHour: sunsetTimeArray[0], sunsetMin: sunsetTimeArray[1], city: cityName, tempUnit: self.tempformat.rawValue)
                                                BluetoothManager.shared.sendWeather(weather: newWeatherInfo)
                                            }
                                            
                                        }
                                    }
                                    self.openWeatherRealTimeData = realTimeWeather
                                    self.updateRealTimeWeatherDataTime()
                                    
                                }
                            }
                        }
                        
                    }
                }
            }
        }catch(let error){
            log.debug("encrypt error =\(error )")
        }
    }
    
    func getOpenWeatherForecast(weatherCityName: String){
        if getIsUpdateForecastData() || weatherCityName != oldOpenWeatherCity{
            oldOpenWeatherCity = weatherCityName
            if let lat = cityGPSInfo["lat"], let lon = cityGPSInfo["lon"] {
                AF.request(openweatherForecastWeatherByGPS, parameters: ["lat": lat,"lon":lon]).responseString { (response) in
                    self.isGettingOpenWeather = false
                    switch response.result{
                    case .success(let encryptString):
                        if let decrypt = encryptString.threeDESEncryptOrDecrypt(op: 0){
                            self.parseOpenWeatherForecast(json: decrypt)
                        }
                    case .failure(let error):
                        log.debug(error)
                    }
                }
            }else {
                AF.request(openweatherForecastWeather, parameters: ["city": weatherCityName]).responseString { (response) in
                    switch response.result{
                    case .success(let encryptString):
                        if let decrypt = encryptString.threeDESEncryptOrDecrypt(op: 0){
                            self.parseOpenWeatherForecast(json: decrypt)
                        }
                    case .failure(let error):
                        log.debug(error)
                    }
                }
            }
        }else {
            if self.OpenWeatherForecastData != nil {
                var forecast = [[String]]()
                for data in OpenWeatherForecastData{
                    if let type = data["type"] as? String, let min = data["min"] as? Double, let max = data["max"] as? Double{
                        var minTempInt = Int(lround(min))
                        var maxTempInt = Int(lround(max))
                        if self.tempformat == .fahrenheit{
                            minTempInt = Int(min * 1.8) + 32
                            maxTempInt = Int(max * 1.8) + 32
                        }
                        forecast.append([type, String(minTempInt), String(maxTempInt), type])
                    }
                }
                if forecast.count > 0{
                    self.writeForecast(forecast)
                }
            }
        }
    }
    
    func parseOpenWeatherForecast(json: String){
        do {
            if let data = json.data(using: .utf8){
                let ditc = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                var codeCheck: Bool = false
                if let dataCodeStr = ditc.value(forKey: "cod") as? String, dataCodeStr == "200"{
                    codeCheck = true
                }
                if let dataCodeInt = ditc.value(forKey: "cod") as? Int, dataCodeInt == 200{
                    codeCheck = true
                }
                if codeCheck {
                    if let list = ditc.value(forKey: "list") as? [[String: Any]], list.count > 0{
                        log.debug("list = \(list)")
                        var forecast = [[String]]()
                        var saveforecast = [[String:Any]]()
                        for v in list{
                            if let temp = v["temp"] as? [String: Any]{
                                if let weathers = v["weather"] as? [[String: Any]], weathers.count > 0{
                                    if let weather = weathers.first{
                                        if let typeId = weather["id"] as? Int,let min = temp["min"] as? Double, let max = temp["max"] as? Double{
                                            let type = String(self.parseOpenWeather(typeId))
                                            var minTempInt = Int(lround(min))
                                            var maxTempInt = Int(lround(max))
                                            if self.tempformat == .fahrenheit{
                                                minTempInt = Int(min * 1.8) + 32
                                                maxTempInt = Int(max * 1.8) + 32
                                            }
                                            forecast.append([type, String(minTempInt), String(maxTempInt), type])
                                            saveforecast.append(["type":type, "min":min, "max":max])
                                        }
                                    }
                                }
                            }
                        }
                        self.writeForecast(forecast)
                        self.OpenWeatherForecastData = saveforecast
                        self.updateForecastDataDateTime()
                    }
                }
            }
        }catch(let error){
            log.debug("encrypt error =\(error )")
        }
    }
    
    func getRealTime() -> Int {
        let realTime = Int(Date().timeIntervalSince1970)
        return realTime
    }
    
    func updateForecastDataDateTime(){
        let dateStr = getRealTime()
        UserDefaults.standard.set(dateStr, forKey: "forecastDataDate")
    }
    
    func getIsUpdateForecastData() -> Bool{
        var isUpdate = true
        if let oldDate = UserDefaults.standard.value(forKey: "forecastDataDate") as? Int{
            let dateInt = getRealTime()
            let countTime = abs(dateInt - oldDate)
            if countTime < 7200{
                isUpdate = false
            }
        }
        return isUpdate
    }
    
    func updateRealTimeWeatherDataTime(){
        let dateInt = getRealTime()
        UserDefaults.standard.set(dateInt, forKey: "RealTimeWeatherDataDate")
    }
    
    func getIsUpdateRealTimeWeatherData() -> Bool{
        var isUpdate = true
        if let oldDate = UserDefaults.standard.value(forKey: "RealTimeWeatherDataDate") as? Int{
            let dateInt = getRealTime()
            let countTime = abs(dateInt - oldDate)
            if countTime < 3600{
                isUpdate = false
            }
        }
        return isUpdate
    }
    
    
    // MARK: 发送天气数据
    func writeForecast(_ weathers:[[String]]) {
        var models = [CRPForecastWeather]()
        for weather in weathers {
            let weathType = Int(weather[0]) as! Int
            let low = Int(weather[1]) as! Int
            let high = Int(weather[2]) as! Int
            let model = CRPForecastWeather(type: weathType, maxTemp: high, minTemp: low)
            models.append(model)
        }
        BluetoothManager.shared.sendForecastWeather(weathers: models)
    }
    
    private func parseType(_ weather:String)->Int{
        let types:Dictionary<String, Int> = ["云":0, "雾":1, "阴":2, "雨":3, "雪":4, "晴":5, "尘":6, "霾":7]
        var type = 2
        guard let weatherInt = Int.init(weather) else {
            return type
        }
        if weatherInt == 100 {
            type = 5
        }else if weatherInt <= 103{
            type = 0
        }else if weatherInt <= 213{
            type = 2
        }else if weatherInt <= 313{
            type = 3
        }else if weatherInt <= 407{
            type = 4
        }else if weatherInt <= 501{
            type = 1
        }else if weatherInt <= 502{
            type = 7
        }else if weatherInt <= 508{
            type = 6
        }
        
        return type
    }
    
    private func parseOpenWeather(_ code:Int)->Int{
        let types:Dictionary<String, Int> = ["云":0, "雾":1, "阴":2, "雨":3, "雪":4, "晴":5, "尘":6, "霾":7]
        var type = 2
        if (code == 800) {
            type = 5
        } else if (code == 721 || code == 711) {
            type = 7
        } else if (code == 741 || code == 701) {
            type = 1
        } else if (600 <= code && code < 700) {
            type = 4
        } else if (code < 600) {
            type = 3
        } else if (800 < code) {
            type = 0
        } else if (731 == code) {
            type = 6
        } else  {
            type = 2
        }
        
        return  type
    }
    
    private func parseYahooType(_ code:String)->Int{
        let types:Dictionary<String, Int> = [
            "0" : 6, "1" : 6, "2" : 6, "3" : 3, "4" : 3, "5" : 3, "6" : 3, "7" : 3, "8" : 3, "9" : 3, "10" : 3, "11" : 3, "12" : 3, "13" : 4, "14" : 4, "15" : 4, "16" : 4, "17" : 4, "18" : 4, "19" : 1, "20" : 1, "21" : 7, "22" : 7, "23" : 2, "24" : 2, "25" : 2, "26" : 0, "27" : 0, "28" : 0, "29" : 0, "30" : 0, "31" : 5, "32" : 5, "33" : 5, "34" : 5, "35" : 3, "36" : 5, "37" : 3, "38" : 3, "39" : 3, "40" : 3, "41" : 4, "42" : 4, "43" : 4, "44" : 0, "45" : 3, "46" : 4, "47" : 3
            ]
        var type = 0
        if types[code] != nil {
            type = types[code]!
        }
        return type
    }
}

private let api2Base = "https://api.moyoung.com"
private let newAPIWeatherCN = api2Base + "/weather-report" // 加密的国内天气
private let openWeatherCurrentWeatherByGPS = "https://wr.moyoung.com/v2/wr"
private let openweatherForecastWeatherByGPS = "https://wr.moyoung.com/v2/wr-7"
private let openWeatherCurrentWeather = "https://wr.moyoung.com/v1/wr"
private let openweatherForecastWeather = "https://wr.moyoung.com/v1/wr-7"

func changeTimeTo24Format(time: String) ->[Int]{
    var timeStr = time
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    dateFormatter.calendar = Calendar.init(identifier: .gregorian)
   
    let am: String = dateFormatter.amSymbol
    let pm: String = dateFormatter.pmSymbol
    var isPm = false
    var isAm = false
    if time.contains(am){
        timeStr = timeStr.replacingOccurrences(of: am, with: "")
        timeStr = timeStr.replacingOccurrences(of: " ", with: "")
        isAm = true
    }
    if time.contains(pm){
        timeStr = timeStr.replacingOccurrences(of: pm, with: "")
        timeStr = timeStr.replacingOccurrences(of: " ", with: "")
        isPm = true
    }
    let timeArr = timeStr.components(separatedBy: ":")
    var timeIntArr = [0,0]
    if timeArr.count == 2{
        timeIntArr[0] = Int(timeArr[0]) ?? 0
        if isAm && timeIntArr[0] == 12{
            timeIntArr[0] = 0
        }
        if isPm && timeIntArr[0] < 12{
            timeIntArr[0] += 12
        }
        timeIntArr[1] = Int(timeArr[1]) ?? 0
        
    }
    return timeIntArr
    
}

